Certainly! Here are some examples of for loops in Java for various use cases:
Example : Counting from 1 to 10 using for loop in java
Counting from 1 to 10
public class Main{
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
}
}
Output
1 2 3 4 5 6 7 8 9 10
This for loop counts from 1 to 10 and prints each number.
Example : Summing Numbers from 1 to 100:
Total sum from 1 to 100 using for loop
public class Main{
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("The sum of numbers from 1 to 100 is: " + sum);
}
}
Output
The sum of numbers from 1 to 100 is: 5050
Here, the for loop is used to calculate the sum of numbers from 1 to 100.
Example : Printing Even Numbers from 2 to 20
Even numbers from 2 to 20 using for loop
public class Main{
public static void main(String[] args) {
for (int i = 2; i <= 20; i += 2) {
System.out.print(i + " ");
}
}
}
Output
2 4 6 8 10 12 14 16 18 20
This for loop prints even numbers from 2 to 20.
Example : Iterating Over an Array
Array iteration using for loop
public class Main{
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Output
10 20 30 40 50
In this example, the for loop is used to iterate over an array of integers and print each element.
Example : Nested for Loop for a Pattern
Pattern printing using for loop
public class Main{
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output
*
* *
* * *
* * * *
* * * * *
This nested for loop prints a pattern of asterisks, creating a triangle.
Example : Looping Through a String
Looping over a string in java
public class Main{
public static void main(String[] args) {
String message = "Hello, Java!";
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i) + " ");
}
}
}
Output
H e l l o , J a v a !
Here, the for loop iterates through the characters of a string and prints each character.
Example : Printing a Countdown
Countdown from 10 example in java
public class Main{
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
}
}
Output
10 9 8 7 6 5 4 3 2 1
This for loop counts down from 10 to 1 and prints each number.
Example : Calculating Factorial
Factorial calculation example in java
public class Main{
public static void main(String[] args) {
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial of " + n + " is: " + factorial);
}
}
Output
Factorial of 5 is: 120
In this example, the for loop is used to calculate the factorial of a number.